<template>
  <div class="customer-stats-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-cards">
      <el-card shadow="hover" v-for="(card, index) in summaryCards" :key="index">
        <div class="card-content">
          <div class="card-icon" :style="{ backgroundColor: card.color }">
            <el-icon :size="20">
              <component :is="card.icon" />
            </el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">{{ card.title }}</div>
            <div class="card-value">{{ card.value }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 前三名奖牌榜 -->
    <div class="podium-section">
      <div class="podium-item silver">
        <div class="medal">🥈</div>
        <div v-if="tableData.length > 1" class="podium-customer">
          <div class="rank">2</div>
          <div class="cid">ID: {{ tableData[1].cid }}</div>
          <div class="name">{{ tableData[1].name }}</div>
          <div class="company" v-if="tableData[1].company">{{ tableData[1].company }}</div>
          <div class="amount">¥{{ formatMoney(tableData[1].cce) }}</div>
        </div>
      </div>

      <div class="podium-item gold">
        <div class="medal">🥇</div>
        <div v-if="tableData.length > 0" class="podium-customer">
          <div class="rank">1</div>
          <div class="cid">ID: {{ tableData[0].cid }}</div>
          <div class="name">{{ tableData[0].name }}</div>
          <div class="company" v-if="tableData[0].company">{{ tableData[0].company }}</div>
          <div class="amount">¥{{ formatMoney(tableData[0].cce) }}</div>
        </div>
      </div>

      <div class="podium-item bronze">
        <div class="medal">🥉</div>
        <div v-if="tableData.length > 2" class="podium-customer">
          <div class="rank">3</div>
          <div class="cid">ID: {{ tableData[2].cid }}</div>
          <div class="name">{{ tableData[2].name }}</div>
          <div class="company" v-if="tableData[2].company">{{ tableData[2].company }}</div>
          <div class="amount">¥{{ formatMoney(tableData[2].cce) }}</div>
        </div>
      </div>
    </div>

    <!-- 消费趋势图表 -->
    <div class="chart-section">
      <el-card shadow="hover">
        <div class="chart-title">客户消费TOP10（按公司）</div>
        <div ref="chartRef" style="height: 350px;"></div>
      </el-card>
    </div>

    <!-- 客户排名表格 -->
    <div class="table-section">
      <el-card shadow="hover">
        <div class="table-header">
          <h3>Top10详细排名</h3>
          <div class="search-box">
            <!-- <el-input v-model="searchParams.keyword" placeholder="搜索客户/公司" clearable @clear="loadData"
              @keyup.enter="loadData" size="small">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input> -->
            <!-- <el-button type="primary" @click="loadData" size="small">搜索</el-button> -->
          </div>
        </div>

        <el-table :data="tableData" border stripe v-loading="loading" :empty-text="emptyText">
          <el-table-column label="排名" width="80" align="center">
            <template #default="{ $index }">
              <el-tag :type="getRankType($index + 1)">
                {{ $index + 1 }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="客户ID" prop="cid" width="120" align="center">
            <template #default="{ row }">
              <el-tag type="info">{{ row.cid }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="客户信息" min-width="180">
            <template #default="{ row }">
              <div class="customer-info">
                <div class="name">{{ row.name }}</div>
                <div class="company" v-if="row.company">{{ row.company }}</div>
                <div class="no-company" v-else>未登记公司</div>
              </div>
            </template>
          </el-table-column>


          <el-table-column prop="cce" label="消费总额(元)" sortable align="right" width="180">
            <template #default="{ row }">
              <span class="money-text">¥{{ formatMoney(row.cce) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="active_count" label="活跃订单" sortable align="center" width="120">
            <template #default="{ row }">
              <el-tag :type="getCountType(row.active_count)">
                {{ row.active_count }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="cpq" label="购买总量" sortable align="center" width="120">
            <template #default="{ row }">
              <el-tag type="success">
                {{ row.cpq }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination v-model:current-page="currentPage" :page-size="pageSize" layout="prev, pager, next"
            :total="totalCount" @current-change="handlePageChange" />
        </div>
      </el-card>
    </div>
  </div>
</template>
 
<script>
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { BarChart } from 'echarts/charts'
import { GridComponent, TooltipComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import * as echarts from 'echarts'
import {
  Search,
  TrendCharts,
  Money,
  List,
  Trophy
} from '@element-plus/icons-vue'
import { customer_StatsAPI } from '@/api/api'

use([BarChart, GridComponent, TooltipComponent, CanvasRenderer])

export default {
  name: 'CustomerStats',
  components: { Search },
  setup() {
    // 图表实例 
    const chartRef = ref(null)
    let chartInstance = null

    // 数据状态
    const loading = ref(false)
    const tableData = ref([])
    const emptyText = ref('暂无数据')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalCount = ref(0)
    const searchParams = ref({ keyword: '' })

    // 统计卡片数据 
    const summaryCards = computed(() => [
      {
        title: '优质客户',
        value: tableData.value.length,
        icon: List,
        color: '#409EFF'
      },
      {
        title: '消费总额',
        value: '¥' + formatMoney(tableData.value.reduce((sum, item) => sum + (item.cce || 0), 0)),
        icon: Money,
        color: '#67C23A'
      },
      {
        title: '总订单数',
        value: tableData.value.reduce((sum, item) => sum + (item.active_count || 0), 0),
        icon: TrendCharts,
        color: '#E6A23C'
      },
      {
        title: 'TOP1客户',
        value: tableData.value[0]?.name || '暂无',
        icon: Trophy,
        color: '#F56C6C'
      }
    ])

    // 加载数据 
    const loadData = async () => {
      loading.value = true
      try {
        const res = await customer_StatsAPI({
          page: currentPage.value,
          size: pageSize.value,
          keyword: searchParams.value.keyword
        })

        if (res.code === 200 && res.data?.data) {
          tableData.value = res.data.data
          totalCount.value = res.data.total || 0
          emptyText.value = tableData.value.length ? '' : '暂无数据'
          renderChart()
        } else {
          tableData.value = []
          emptyText.value = '暂无数据'
        }
      } catch (error) {
        console.error(' 加载数据失败:', error)
        emptyText.value = '加载失败'
      } finally {
        loading.value = false
      }
    }

    // 渲染图表（重点修改部分）
    const renderChart = () => {
      if (!chartRef.value || tableData.value.length === 0) return

      // 处理数据：优先使用公司名，没有则用客户名 
      const chartData = [...tableData.value]
        .sort((a, b) => b.cce - a.cce)
        .slice(0, 10)
        .map(item => ({
          name: item.company || item.name,
          value: item.cce
        }))

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: params => {
            const data = params[0]
            return `
              <div style="font-weight:bold;margin-bottom:5px">${data.name}</div> 
              <div>消费总额: ¥${formatMoney(data.value)}</div> 
            `
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '20%', // 为X轴标签留更多空间 
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: chartData.map(item => item.name),
          axisLabel: {
            interval: 0, // 强制显示所有标签 
            fontSize: 10,
            width: 80,
            overflow: 'truncate',
            ellipsis: '...',
            formatter: value => {
              // 超过6个字符显示省略号
              return value.length > 6 ? value.substring(0, 5) + '...' : value
            },
            margin: 25 // 标签与轴线距离 
          },
          axisTick: {
            alignWithLabel: true,
            length: 5
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: value => '¥' + formatMoney(value)
          }
        },
        series: [{
          name: '消费金额',
          type: 'bar',
          barWidth: '40%',
          data: chartData.map(item => item.value),
          itemStyle: {
            color: params => {
              const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de']
              return colors[params.dataIndex % colors.length]
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: params => '¥' + formatMoney(params.value)
          }
        }]
      }

      if (!chartInstance) {
        chartInstance = echarts.init(chartRef.value)
      }
      chartInstance.setOption(option)
    }

    // 工具函数
    const formatMoney = (value) => {
      if (value === null || value === undefined) return '0.00'
      return Number(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }

    const getRankType = (rank) => {
      if (rank === 1) return 'danger'
      if (rank <= 3) return 'warning'
      if (rank <= 10) return 'success'
      return ''
    }

    const getCountType = (count) => {
      if (count > 50) return 'danger'
      if (count > 20) return 'warning'
      if (count > 5) return 'success'
      return 'info'
    }

    const handlePageChange = (page) => {
      currentPage.value = page
      loadData()
    }

    // 初始化 
    onMounted(() => {
      loadData()
      window.addEventListener('resize', () => {
        chartInstance?.resize()
      })
    })

    return {
      // 引用 
      chartRef,

      // 数据 
      loading,
      tableData,
      emptyText,
      currentPage,
      pageSize,
      totalCount,
      searchParams,
      summaryCards,

      // 方法 
      loadData,
      formatMoney,
      getRankType,
      getCountType,
      handlePageChange
    }
  }
}
</script>
 
<style lang="scss" scoped>
.customer-stats-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 15px;

  .el-card {
    border-radius: 8px;

    :deep(.el-card__body) {
      padding: 15px;
    }
  }

  .card-content {
    display: flex;
    align-items: center;
    gap: 15px;

    .card-icon {
      width: 40px;
      height: 40px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
    }

    .card-info {
      flex: 1;

      .card-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 5px;
      }

      .card-value {
        font-size: 18px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
}

.podium-section {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 20px;
  margin: 30px 0;

  .podium-item {
    flex: 1;
    max-width: 220px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .medal {
      font-size: 60px;
      line-height: 1;
      margin-bottom: 15px;
    }

    .podium-customer {
      text-align: center;
      padding: 15px;
      border-radius: 8px;
      width: 100%;
      min-height: 120px;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .rank {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 5px;
      }

      .cid{
        font-size: 12px;
      }
      .name {
        font-size: 16px;
        margin-bottom: 3px;
        font-weight: 500;
      }

      .company {
        font-size: 12px;
        color: #666;
        margin-bottom: 5px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .amount {
        font-size: 14px;
        color: #67C23A;
        font-weight: bold;
      }
    }

    &.gold {
      .podium-customer {
        background: linear-gradient(135deg, #FFF9E6 0%, #FFE7BA 100%);
        border: 1px solid #FFD77A;
      }
    }

    &.silver {
      .podium-customer {
        background: linear-gradient(135deg, #F5F5F5 0%, #E0E0E0 100%);
        border: 1px solid #C0C0C0;
      }
    }

    &.bronze {
      .podium-customer {
        background: linear-gradient(135deg, #F9F0E6 0%, #E8D0B0 100%);
        border: 1px solid #D4A76A;
      }
    }
  }
}

.chart-section {
  .el-card {
    border-radius: 8px;

    :deep(.el-card__body) {
      padding: 15px;
      height: 400px;
      /* 增加高度适应垂直标签 */
    }

    .chart-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #303133;
    }
  }
}

.table-section {
  .el-card {
    border-radius: 8px;

    :deep(.el-card__body) {
      padding: 0;
    }
  }

  .table-header {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #EBEEF5;

    h3 {
      margin: 0;
      font-size: 16px;
    }

    .search-box {
      display: flex;
      gap: 10px;
    }
  }

  .customer-info {
    .name {
      font-weight: 500;
      margin-bottom: 3px;
    }

    .company {
      font-size: 12px;
      color: #666;
    }

    .no-company {
      font-size: 12px;
      color: #999;
      font-style: italic;
    }
  }

  .money-text {
    font-weight: bold;
    color: #E6A23C;
  }

  .pagination {
    padding: 15px;
    display: flex;
    justify-content: flex-end;
  }
}

@media (max-width: 768px) {
  .podium-section {
    flex-direction: column;
    align-items: center;
    gap: 15px;

    .podium-item {
      max-width: 100%;
      width: 100%;

      .podium-customer {
        min-height: auto;
        padding: 10px;
      }
    }
  }

  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .stats-cards {
    grid-template-columns: 1fr 1fr;
  }
}
</style>